//
//  OAuthViewController.swift
//  Weibo
//
//  Created by 李亚乐 on 15/12/8.
//  Copyright © 2015年 李亚乐. All rights reserved.
//

import UIKit
import SVProgressHUD
/// 授权页面
class OAuthViewController: UIViewController {
    private lazy var webView = UIWebView()
    
//MARK: - 加载视图
    override func loadView() {

        view = webView
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: UIBarButtonItemStyle.Plain, target: self, action: "closeView")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: UIBarButtonItemStyle.Plain, target: self, action: "autoFill")
        title = "登陆新浪微博"
        
    }
    
//MARK: - 视图已加载
    override func viewDidLoad() {
        super.viewDidLoad()
        webView.delegate = self
        webView.loadRequest(NSURLRequest(URL: NetworkTools().OAuthURL))
    }
    
    /// 关闭视图
    @objc private func closeView() {
        
        SVProgressHUD.dismiss()
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    /// 自动填充
    @objc private func autoFill() {
        let js = "document.getElementById('userId').value = 'lyl921101@gmail.com';" +
        "document.getElementById('passwd').value = '19921101';"
        
        webView.stringByEvaluatingJavaScriptFromString(js)
    }
}

// MARK: - webView 代理方法
extension OAuthViewController: UIWebViewDelegate {
    
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }
    
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
    /// 是否允许加载 With请求
    ///
    /// - parameter webView:        webView
    /// - parameter request:        请求头
    /// - returns:      false: 不加载, true: 继续加载
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        //守卫百度 否则继续
        guard let url = request.URL where url.host == "www.baidu.com" else {
            
            return true
        }
        
        // 守卫 query :? 请求参数 前缀为 "code=" 否则不继续加载
        guard let query = url.query where query.hasPrefix("code=") else {
            closeView()
            return false
        }
        
        /// 授权码 code:
        let code = query.substringFromIndex("code=".endIndex)
        
//MARK: -  加载 AccessToken
        UserAccountViewModel.sharedUserAccount.loadUserAccessToken(code) { (isSuccessed) -> () in
            
            if !isSuccessed {
                SVProgressHUD.showErrorWithStatus("网络不给力~")
                delay(1.0, callFunc: { () -> () in
                    self.closeView()
                })
                return
            }
            
            print("成功了")
            print(UserAccountViewModel.sharedUserAccount.account)
            
            self.dismissViewControllerAnimated(false, completion: { () -> Void in
                
                SVProgressHUD.dismiss()
                
                NSNotificationCenter.defaultCenter().postNotificationName(WBSwitchRootControllerNotification, object: "welcome")
            })
        }
        
        return false
    }
}

